const Mock = require('mockjs')
const bodyParser = require('body-parser')

function registerRoutes(app) {
  let mockLastIndex
  const { mocks } = require('./index')
  const mocksForServer = mocks.map((route) => {
    return responseFake(route.url, route.type, route.response)
  })

  for (const mock of mocksForServer) {
    app[mock.type](mock.url, mock.response)
    mockLastIndex = app._router.stack.length
  }
  const mockRoutesLength = Object.keys(mocksForServer).length
  return {
    mockRoutesLength: mockRoutesLength,
    mockStartIndex: mockLastIndex - mockRoutesLength,
  }
}

// for mock server
const responseFake = (url, type, respond) => {
  console.log(
    'url = ' + url + 'type = ' + type + 'respond =' + JSON.stringify(respond)
  )
  let item = {
    url: new RegExp(`${process.env.VUE_APP_BASE_URL}${url}`),
    type: type || 'get',
    response(req, res) {
      res.json(
        Mock.mock(respond instanceof Function ? respond(req, res) : respond)
      )
    },
  }
  return item
}
module.exports = (app) => {
  // TODO 为什么加了这个就能解析出来body
  app.use(bodyParser.json())
  app.use(
    bodyParser.urlencoded({
      extended: true,
    })
  )
  registerRoutes(app)
}
